'use strict';

// 云函数入口函数
exports.main = async (event, context) => {
  // 获取数据库引用
  const db = uniCloud.database();
  const dbCmd = db.command;
  
  try {
    console.log('开始初始化数据库...');
    
    // 创建管理员账号
    await createAdminUser(db);
    
    // 创建测试数据
    await createTestData(db);
    
    return {
      code: 0,
      message: '数据库初始化成功'
    };
  } catch (e) {
    console.error('数据库初始化失败：', e);
    return {
      code: -1,
      message: '数据库初始化失败',
      error: e
    };
  }
};

// 创建管理员账号
async function createAdminUser(db) {
  const usersCollection = db.collection('users');
  
  // 检查管理员账号是否已存在
  const adminUser = await usersCollection.where({
    username: 'admin'
  }).get();
  
  if (adminUser.data.length === 0) {
    // 创建管理员账号
    await usersCollection.add({
      username: 'admin',
      password: '21232f297a57a5a743894a0e4a801fc3', // admin的md5加密
      email: 'admin@referee.com',
      phone: '13800000000',
      role: 3, // 3-管理员
      create_date: new Date(),
      status: 1
    });
    console.log('管理员账号创建成功');
  } else {
    console.log('管理员账号已存在');
  }
}

// 创建测试数据
async function createTestData(db) {
  // 创建测试用户
  await createTestUsers(db);
  
  // 创建示例规则内容
  await createSampleRules(db);
  
  // 创建示例视频内容
  await createSampleVideos(db);
  
  // 创建示例考试题目
  await createSampleQuestions(db);
}

// 创建测试用户
async function createTestUsers(db) {
  const usersCollection = db.collection('users');
  
  // 检查测试用户是否已存在
  const testUser = await usersCollection.where({
    username: 'referee_test'
  }).get();
  
  if (testUser.data.length === 0) {
    // 创建裁判员测试账号
    const refereeUser = await usersCollection.add({
      username: 'referee_test',
      password: 'e10adc3949ba59abbe56e057f20f883e', // 123456的md5加密
      email: 'referee@test.com',
      phone: '13800000001',
      role: 1, // 1-裁判员
      create_date: new Date(),
      status: 1
    });
    
    // 创建裁判员资质信息
    await db.collection('referee_credentials').add({
      user_id: refereeUser.id,
      certificate_no: 'R2023001',
      register_date: new Date('2023-01-01'),
      expire_date: new Date('2025-12-31'),
      level: 2,
      issuing_authority: '中国足球协会',
      verified: true
    });
    
    // 创建裁判监督测试账号
    const adminUser = await usersCollection.add({
      username: 'admin_test',
      password: 'e10adc3949ba59abbe56e057f20f883e', // 123456的md5加密
      email: 'admin@test.com',
      phone: '13800000002',
      role: 3, // 3-裁判监督
      create_date: new Date(),
      status: 1
    });
    
    // 创建裁判监督资质信息
    await db.collection('supervisor_credentials').add({
      user_id: adminUser.id,
      certificate_no: 'S2023001',
      register_date: new Date('2023-01-01'),
      expire_date: new Date('2025-12-31'),
      level: 2,
      issuing_authority: '中国足球协会',
      verified: true
    });
    
    console.log('测试用户创建成功');
  } else {
    console.log('测试用户已存在');
  }
}

// 创建示例规则内容
async function createSampleRules(db) {
  const rulesCollection = db.collection('rule_contents');
  
  // 检查示例规则是否已存在
  const sampleRule = await rulesCollection.where({
    title: '足球比赛规则 - 规则一：球场'
  }).get();
  
  if (sampleRule.data.length === 0) {
    // 创建示例规则内容
    await rulesCollection.add({
      title: '足球比赛规则 - 规则一：球场',
      content: '# 规则一：球场\n\n## 场地表面\n比赛场地表面必须是全部天然的或者，如果竞赛规程允许，全部人造的，除非竞赛规程允许天然和人造材料的结合使用（混合系统）。\n\n人造场地表面必须是绿色的。\n\n当在国际足联会员协会之间的代表队比赛或国际俱乐部比赛中使用人造场地时，除非国际足球理事会特别准许，否则场地表面必须符合国际足联人造草皮品质要求或国际人造草皮标准。\n\n## 场地标记\n比赛场地必须是长方形，并用连续的线进行标记，这些线不得构成危险。这些线属于它们所划定区域的一部分。\n\n只有规则一中所描述的线可以被标记在比赛场地上。\n\n两条较长的边界线叫做边线。两条较短的线叫做球门线。\n\n比赛场地被一条连接两条边线中点的中线分成两半。\n\n中点标记在中线的中点位置。以中点为中心，划一条半径为9.15米（10码）的圆圈。\n\n场地外距角旗杆9.15米（10码）处，可以在球门线和边线上分别垂直地做标记。\n\n所有的线必须具有相同的宽度，且不能超过12厘米（5英寸）。球门线必须与球门柱和横梁的宽度相同。\n\n如果有人使用非法标记场地，将被竞赛组织者根据其违规行为进行处罚。',
      summary: '足球比赛规则第一条：球场的相关规定，包括场地表面、场地标记等内容',
      language: 'zh-CN',
      category: '比赛规则',
      tags: ['球场', '场地标记', '基础规则'],
      version: '2022/23',
      create_date: new Date(),
      update_date: new Date(),
      view_count: 0
    });
    
    await rulesCollection.add({
      title: 'Football Laws of the Game - Law 1: The Field of Play',
      content: '# Law 1: The Field of Play\n\n## Field surface\nThe field of play must be a wholly natural or, if competition rules permit, a wholly artificial playing surface except where competition rules permit an integrated combination of artificial and natural materials (hybrid system).\n\nThe colour of artificial surfaces must be green.\n\nWhere artificial surfaces are used in competition matches between representative teams of national football associations affiliated to FIFA or international club competition matches, the surface must meet the requirements of the FIFA Quality Programme for Football Turf or the International Match Standard, unless special dispensation is given by The IFAB.\n\n## Field markings\nThe field of play must be rectangular and marked with continuous lines which must not be dangerous; artificial playing surface material may be used for the field markings on natural fields if it is not dangerous. These lines belong to the areas of which they are boundaries.\n\nOnly the lines indicated in Law 1 are to be marked on the field of play.\n\nThe two longer boundary lines are touchlines. The two shorter lines are goal lines.\n\nThe field of play is divided into two halves by a halfway line, which joins the midpoints of the two touchlines.\n\nThe centre mark is at the midpoint of the halfway line. A circle with a radius of 9.15 m (10 yds) is marked around it.\n\nMarks may be made off the field of play 9.15 m (10 yds) from the corner arc and at right angles to the goal lines and the touchlines.\n\nAll lines must be of the same width, which must not be more than 12 cm (5 ins). The goal lines must be of the same width as the goalposts and the crossbar.\n\nA player who makes unauthorised marks on the field of play must be cautioned for unsporting behaviour. If the referee notices this being done during the match, the player is cautioned when the ball next goes out of play.',
      summary: 'Law 1 of the Football Laws of the Game: The Field of Play, including field surface and field markings requirements',
      language: 'en',
      category: 'Game Rules',
      tags: ['field', 'markings', 'basic rules'],
      version: '2022/23',
      create_date: new Date(),
      update_date: new Date(),
      view_count: 0
    });
    
    console.log('示例规则内容创建成功');
  } else {
    console.log('示例规则内容已存在');
  }
}

// 创建示例视频内容
async function createSampleVideos(db) {
  const videosCollection = db.collection('learning_videos');
  
  // 检查示例视频是否已存在
  const sampleVideo = await videosCollection.where({
    title: '足球越位规则详解'
  }).get();
  
  if (sampleVideo.data.length === 0) {
    // 创建示例视频内容
    await videosCollection.add({
      title: '足球越位规则详解',
      description: '详细讲解足球比赛中的越位规则，包含多个实例分析和判罚标准',
      video_url: 'https://example.com/videos/offside-rules.mp4',
      cover_image: 'https://example.com/images/offside-rules-cover.jpg',
      duration: 1200, // 20分钟
      category: '规则讲解',
      tags: ['越位', '裁判判罚', '进阶规则'],
      difficulty_level: 2,
      create_date: new Date(),
      update_date: new Date(),
      view_count: 0,
      like_count: 0
    });
    
    await videosCollection.add({
      title: '裁判手势与哨音技巧',
      description: '专业裁判示范比赛中各种手势的标准动作和哨音的使用技巧',
      video_url: 'https://example.com/videos/referee-signals.mp4',
      cover_image: 'https://example.com/images/referee-signals-cover.jpg',
      duration: 900, // 15分钟
      category: '技能培训',
      tags: ['手势', '哨音', '基础技能'],
      difficulty_level: 1,
      create_date: new Date(),
      update_date: new Date(),
      view_count: 0,
      like_count: 0
    });
    
    console.log('示例视频内容创建成功');
  } else {
    console.log('示例视频内容已存在');
  }
}

// 创建示例考试题目
async function createSampleQuestions(db) {
  const questionsCollection = db.collection('exam_questions');
  
  // 检查示例题目是否已存在
  const sampleQuestion = await questionsCollection.where({
    question: '以下哪种情况下，球员不处于越位位置？'
  }).get();
  
  if (sampleQuestion.data.length === 0) {
    // 创建示例考试题目
    await questionsCollection.add({
      question: '以下哪种情况下，球员不处于越位位置？',
      question_type: 1, // 单选题
      options: [
        { key: 'A', content: '在本方半场' },
        { key: 'B', content: '与倒数第二名防守球员同一水平线' },
        { key: 'C', content: '在对方球门线后' },
        { key: 'D', content: '接到守门员踢出的球门球' }
      ],
      correct_answer: 'A',
      explanation: '根据越位规则，球员在本方半场不可能处于越位位置',
      difficulty_level: 1,
      category: '规则理解',
      tags: ['越位', '基础规则'],
      create_date: new Date(),
      update_date: new Date(),
      usage_count: 0
    });
    
    await questionsCollection.add({
      question: '当球队获得角球时，裁判应该站在哪个位置？',
      question_type: 1, // 单选题
      options: [
        { key: 'A', content: '禁区内' },
        { key: 'B', content: '角球区附近' },
        { key: 'C', content: '与主裁判成三角形位置' },
        { key: 'D', content: '球门线上' }
      ],
      correct_answer: 'C',
      explanation: '角球时，裁判员应该与主裁判和开角球点形成一个三角形，以便观察可能的犯规和进球',
      difficulty_level: 2,
      category: '裁判站位',
      tags: ['角球', '裁判技术'],
      create_date: new Date(),
      update_date: new Date(),
      usage_count: 0
    });
    
    console.log('示例考试题目创建成功');
  } else {
    console.log('示例考试题目已存在');
  }
} 